#include <iostream>
#include <cstdio>
#include <cstring>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/syscall.h> //仅仅是了解

using namespace std;

// // 带__thread 给每个线程拷一份
// __thread int global_value = 100;

// void *startRoutine(void *args)
// {
//     //线程分离
//     //pthread_detach(pthread_self());
//     while (true)
//     {
//         cout << "thread " << pthread_self() << " global_value: "
//              << global_value << " &global_value: " << &global_value
//              << " Inc: " << global_value++ << " lwp: " << ::syscall(SYS_gettid) << endl;
//         sleep(1);
//     }
//}

int tickets = 10000; // 临界资源
pthread_mutex_t mutex;//定义锁
void *getTickets(void *args)
{
    const char *name = static_cast<const char *>(args);
    while (true)
    {
        //临界区
        pthread_mutex_lock(&mutex);
        if (tickets > 0)
        {
            usleep(1000);
            cout << name << " 抢到了票,票的编号是：" << tickets << endl;
            tickets--;
            pthread_mutex_unlock(&mutex);
            usleep(1000);
        }
        else
        {
            
            cout << name << " 已经放弃抢票了，因为没有票了....." << endl;
            pthread_mutex_unlock(&mutex);
            break;
        }
    }
    return nullptr;
}

int main()
{
    pthread_mutex_init(&mutex,nullptr);
    pthread_t tid1;
    pthread_t tid2;
    pthread_t tid3;

    pthread_create(&tid1, nullptr, getTickets, (void *)"thread 1");
    pthread_create(&tid2, nullptr, getTickets, (void *)"thread 2");
    pthread_create(&tid3, nullptr, getTickets, (void *)"thread 3");

    // sleep(1);

    // // 倾向于让主线程分离其他线程
    // pthread_detach(tid1);
    // pthread_detach(tid2);
    // pthread_detach(tid3);

    // 一旦分离不能join
    int n1 = pthread_join(tid1, nullptr);
    cout << "strerror(n1): " << strerror(n1) << endl;
    int n2 = pthread_join(tid2, nullptr);
    cout << "strerror(n2): " << strerror(n2) << endl;
    int n3 = pthread_join(tid3, nullptr);
    cout << "strerror(n3): " << strerror(n3) << endl;

    pthread_mutex_destroy(&mutex);
    return 0;
}
